﻿using System;
using System.Linq;

namespace N2.Workflow.Edit.Web
{
	using Items;
	
	public partial class Edit : WorkflowEditPage
	{
//TODO inject as dependency
		IWorkflowProvider WorkflowProvider;
		
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			
			this.WorkflowProvider = this.Engine.Resolve<IWorkflowProvider>();

			this.lbExecute.Click += (_sender, _e) => {
				if (wfToolBar.WorkflowActionPerformed) {
					//get just saved concrete child
					ItemState _state = this.wfToolBar.ItemEditor.Save() as ItemState;
					
					this.WorkflowProvider.PerformAction(
						this.SelectedItem,
						_state);
				}

				this.wfToolBar.Reset();
				Response.Redirect(this.SelectedItem.Url);
			};

			this.rpt.ItemCommand += (_sender, _e) => {
				if (string.Equals(_e.CommandName, "SelectAction")) {
					var _action = this.WorkflowProvider.ResolveActionForItem(this.SelectedItem, _e.CommandArgument as string) as ActionDefinition;
					if (null != _action) {
						this.wfToolBar.Reset();
						this.wfToolBar.ParentItem = this.SelectedItem;
						this.wfToolBar.SelectedAction = _action;
					}
				}
			};
			
			this.at.ParentItem = this.wfToolBar.ParentItem = this.SelectedItem;
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			if (!this.IsPostBack) {
				var _provider = this.Engine.Resolve<IWorkflowProvider>();
				var _currentState = _provider.GetCurrentState(this.SelectedItem);
				
				if (null != _currentState) {
					this.rpt.DataSource = _currentState.Definition.Actions.ToList();
					this.rpt.DataBind();
				}
			}
		}
		
		protected override void OnPreRenderComplete(EventArgs e)
		{
			base.OnPreRenderComplete(e);
			this.lbExecute.Visible = this.wfToolBar.WorkflowActionPerformed;
		}
	}
}
